package org.glut.service;

import org.glut.bean.User;
import org.glut.config.MyUserDetils;
import org.glut.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Service
public class MyUserDatailsServeice implements UserDetailsService {
    @Autowired
    private UserDao userDao;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private MessageService messageService;
    @Autowired
    private MyUserDetils myUserDetils;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userDao.getUserByname(username);
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在");
        }else {

        }
//        String encodePassword = passwordEncoder.encode(user.getPassword());
//        user.setPassword(encodePassword);
        String role = user.getRole();
        String[] split = role.split(",");
        List<String> list = new ArrayList<>();
        for (String vip : split) {
            list.add("ROLE_"+vip);
        }
//        System.out.println("list = " + list);
        myUserDetils.setAuthorities(AuthorityUtils.commaSeparatedStringToAuthorityList(String.join(",", list)));
//        System.out.println("权限 ------------"+myUserDetils.getAuthorities());
        myUserDetils.setUsername(username);
        myUserDetils.setPassword(user.getPassword());
        myUserDetils.setEnabled(true);
//        System.out.println("用户：："+myUserDetils.getUsername());
//        System.out.println("密码：："+myUserDetils.getPassword());
        return myUserDetils;
    }
}
